package com.wnxy.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import com.wnxy.admin.common.ResponseResult;
import com.wnxy.admin.common.util.VerifyCodeUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码控制器
 */
@RequestMapping("/code")
@RestController
public class ValiCodeController {
    private final RedisTemplate<String, String> redisTemplate;

    public ValiCodeController(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/generator")
    public ResponseResult generator(@RequestParam String uniqueId) throws IOException {
        //生成验证码逻辑
        String captcha = VerifyCodeUtils.generateCaptchaLogic(4);

        // 将验证码存储在Redis中，以唯一标识为Key
        redisTemplate.opsForValue().set(uniqueId+"", captcha+"", 5, TimeUnit.MINUTES);

        // 将验证码图片的Base64数据返回给前端
        String imgsrc = VerifyCodeUtils.VerifyCode(100, 30, captcha);
        Map<String, String> response = new HashMap<>();
        response.put("imgsrc", imgsrc);
        return ResponseResult.ok(response);
    }

}
